import {Express} from "express";
import {globalConfig} from "../config";
import path from 'path';
import {FileInfo} from "../types";
import {FileUtil} from "../utils/FileUtil";

export function FileService(app: Express) {
  const prefix = '/api/file';

  // 获取根目录
  app.get(prefix + '/root', async (req, res) => {
    try {
      const targetDir = globalConfig.config.scan.targetDir;

      const children = await FileUtil.getDirectoryChildren(targetDir);

      const rootInfo: FileInfo = {
        name: path.basename(targetDir),
        path: targetDir,
        size: 0,
        isDirectory: true,
        hasChildren: true,
        children
      };

      res.json(rootInfo);
    } catch (error) {
      console.error('获取根目录失败:', error);
      res.status(500).json({error: `服务器错误: ${(error as Error).message}`});
    }
  });

  // 获取子目录
  app.get(prefix + '/children:path', async (req, res) => {
    try {
      const path = req.params.path;
      const children = await FileUtil.getDirectoryChildren(path);
      res.json(children);
    } catch (error) {
      console.error('获取子目录失败:', error);
      res.status(500).json({error: `服务器错误: ${(error as Error).message}`});
    }
  });

  // 获取文件夹大小
  app.get(prefix + '/dir/size:path', async (req, res) => {
    try {
      const path = req.params.path;
      const size = await FileUtil.getDirectorySize(path);
      res.json(size);
    } catch (error) {
      console.error('获取文件夹大小失败:', error);
      res.status(500).json({error: `服务器错误: ${(error as Error).message}`});
    }
  });
}
